package cn.edu.tju.wallet.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.wallet.dto.ConfirmRequestDTO;
import cn.edu.tju.wallet.dto.PaymentRequestDTO;
import cn.edu.tju.wallet.dto.RefundRequestDTO;
import cn.edu.tju.wallet.service.PaymentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 支付相关接口
 */
@RestController
@RequestMapping("/api/payment")
@Tag(name = "钱包支付", description = "支付、确认收货、退款接口")
public class PaymentController {

    private final PaymentService paymentService;

    public PaymentController(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @PostMapping("/pay")
    @Operation(summary = "支付", description = "发起支付，付款方资金扣减并冻结到收款方。支持选择是否使用透支额度支付。")
    public HttpResult<Void> payment(@Valid @RequestBody PaymentRequestDTO request) {
        try {
            Boolean allowOverdraft = request.getAllowOverdraft();
            if (allowOverdraft == null) {
                allowOverdraft = false;
            }
            paymentService.payment(request.getPayerId(), request.getReceiverId(), request.getAmount(),
                    request.getOrderId(), allowOverdraft);
            return HttpResult.success();
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    @PostMapping("/confirm")
    @Operation(summary = "确认收货", description = "解冻收款方资金")
    public HttpResult<Void> confirmReceipt(@Valid @RequestBody ConfirmRequestDTO request) {
        try {
            paymentService.confirmReceipt(request.getOrderId());
            return HttpResult.success();
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    @PostMapping("/refund")
    @Operation(summary = "退款", description = "对订单进行退款操作")
    public HttpResult<Void> refund(@Valid @RequestBody RefundRequestDTO request) {
        try {
            paymentService.refund(request.getOrderId());
            return HttpResult.success();
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }
}

